#include "class_strategy_adaptive.h"

extern class_center a;
extern lambda_pool pool;


class_strategy_adaptive::class_strategy_adaptive(int idd, std::string dz, std::string dm, double bj, int sl)
{
memset(&tick,0,sizeof(tick));

name = dm;

std::string str = a.path_str + "/strategy";
create_path(str);

str = a.path_str + "/strategy/adaptive";
create_path(str);

str = a.path_str + "/strategy/adaptive/"+dz;
create_path(str);

str = a.path_str + "/log/strategy";
create_path(str);

str = a.path_str + "/log/strategy/adaptive";
create_path(str);

cc = new class_strategy_position(a.path_str + "/strategy/adaptive/" + dz);
cc->ints[2] = sl;
cc->dous[1]=bj;

id=idd;
a.tick_event_map[name].insert([this](){ pool.insert([this](){ if(a.flag[50]==1){run_one();} }); },id);
a.log.insert("strategy/adaptive/"+name,"实例化成功,当前仓位" + std::to_string(cc->position));
}

class_strategy_adaptive::~class_strategy_adaptive()
{
a.tick_event_map[name].pop(id);
	a.log.insert("strategy/adaptive/"+name,"析构完成,当前仓位"+std::to_string(cc->position));
//std::copy(dous, dous + sizeof(dous) / sizeof(double), cc->dous);
//std::copy(ints, ints + sizeof(ints) / sizeof(int), cc->ints);

delete cc;
}


// 主执行函数
void class_strategy_adaptive::run_one()
{


//清理报单返回值
a.return_erase(*cc);
//同步持仓
a.position_sync(*cc);
//获取到TICK
tick=a.tick_map[name];


//下面是数据计算
if(cc->ints[0] == 1)
{
if(cc->ints[2] < 0)
{
if(tick.LastPrice < cc->dous[0])
{
cc->dous[0] = tick.LastPrice;
}
}
if(cc->ints[2] > 0)
{	
if(tick.LastPrice > cc->dous[0])
{
	cc->dous[0] = tick.LastPrice;
}
}
}
	else
{
cc->dous[0] = tick.LastPrice;
cc->ints[0] = 1;
if(cc->position == 0)
{
cc->position = cc->ints[2];
cc->value = cc->position * tick.LastPrice * -1;
}
return;
}


//下面是报单
//如果处于买入区且仓位不够则
if (cc->position < 0 && tick.LastPrice >= (cc->dous[0] + cc->dous[1]) && cc->return_vector.size() == 0)
{
a.bd_auto(tick.InstrumentID, '0', tick.UpperLimitPrice, 1, *cc);
a.log.insert("strategy/adaptive/" + name +"交易", name + "买入动作" + std::to_string(tick.AskPrice1) + ",关注线:" + std::to_string(cc->dous[0]));
return;
}


if(cc->position > 0 && tick.LastPrice <= (cc->dous[0] - cc->dous[1]) && cc->return_vector.size() == 0)
{
a.bd_auto(tick.InstrumentID, '1', tick.LowerLimitPrice, 1,*cc);
a.log.insert("strategy/adaptive/" + name + "交易", name + "卖出" + std::to_string(tick.BidPrice1) +",关注线:" + std::to_string(cc->dous[0]));
return;
}

return;
}

